import React, { useState } from 'react';
import { Form, Button, Input, Modal } from 'antd';

import { KConfigUpdateItem } from '../data.d';

export interface UpdateFormProps {
  onCancel: (flag?: boolean, formVals?: KConfigUpdateItem) => void;
  onSubmit: (values: KConfigUpdateItem) => void;
  updateModalVisible: boolean;
  values: KConfigUpdateItem;
}
const FormItem = Form.Item;

export interface UpdateFormState {
  formVals: KConfigUpdateItem;
}

const formLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 13 },
};

const UpdateForm: React.FC<UpdateFormProps> = (props) => {
  console.log(props.values.confName);
  const [formValues, setFormValues] = useState<KConfigUpdateItem>({
    key: props.values.key,
    confName: props.values.confName,
    instance: props.values.instance,
    confValue: props.values.confValue,
  });

  const [form] = Form.useForm();

  const {
    onSubmit: handleUpdate,
    onCancel: handleUpdateModalVisible,
    updateModalVisible,
    values,
  } = props;

  const handleRealUpdate = async () => {
    const fieldsValue = await form.validateFields();
    setFormValues({ ...formValues, ...fieldsValue });
    handleUpdate({ ...formValues, ...fieldsValue });
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => handleUpdateModalVisible(false, values)}>取消</Button>
        <Button type="primary" onClick={() => handleRealUpdate()}>修改</Button>
      </>
    );
  };

  return (
    <Modal
      width={640}
      bodyStyle={{ padding: '32px 40px 48px' }}
      destroyOnClose
      title="修改配置项"
      visible={updateModalVisible}
      footer={renderFooter()}
      onCancel={() => handleUpdateModalVisible()}
    >
      <Form
        {...formLayout}
        form={form}
        initialValues={{
          key: formValues.key,
          confName: formValues.confName,
          instance: formValues.instance,
          confValue: formValues.confValue,
        }}
      >
        <FormItem
          name="key"
          label="ID"
        >
          <Input placeholder="请输入" disabled={true} />
        </FormItem>
        <FormItem
          name="confName"
          label="confName"
        >
          <Input placeholder="请输入" disabled={true} />
        </FormItem>
        <FormItem
          name="instance"
          label="instance"
        >
          <Input placeholder="请输入" disabled={true} />
        </FormItem>
        <FormItem
          name="confValue"
          label="value"
        >
          <Input placeholder="请输入" />
        </FormItem>
      </Form>
    </Modal>
  );
};

export default UpdateForm;
